package com.gezi.admin.config.validate.constraint.dict;

import cn.hutool.core.util.StrUtil;
import com.gezi.admin.module.sys.dict.data.AppDictDataService;
import com.gezi.admin.utils.AppContextUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Author 格子代码
 * @createDate 2024/2/10 09:00
 * @contact 1424529270@qq.com
 **/
@Slf4j
public class ValidDictValidator implements ConstraintValidator<ValidDictEnum, Object> {
    private ValidDictEnum annotation;

    @Override
    public void initialize(ValidDictEnum constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (!annotation.isNotEmpty()) {
            return false;
        }

        if(value instanceof String){
            if(StrUtil.isBlank((String)value)){
                return false;
            }
        }
        String mValue = String.valueOf(value);
        if(annotation.isList()){
            for (String s : mValue.split(",")) {
                AppDictDataService appDictDataService = AppContextUtil.getBean(AppDictDataService.class);
                long count = appDictDataService.countAllByTypeAndDataType(annotation.type(),s);
                if(count == 0){
                    return false;
                }
            }
        }else{
            AppDictDataService appDictDataService = AppContextUtil.getBean(AppDictDataService.class);
            long count = appDictDataService.countAllByTypeAndDataType(annotation.type(),mValue);
            if(count == 0){
                return false;
            }
        }

        return true;
    }
}
